package com.learning.security.service;

import com.learning.security.controller.vo.AdminAuthLoginRespVO;
import com.learning.security.controller.vo.AuthLoginReqVO;
import com.learning.security.dal.dataobject.AdminOAuth2AccessTokenDO;
import com.learning.security.dal.dataobject.AdminUserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class AdminAuthServiceImpl implements AdminAuthService {

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private AdminOAuth2TokenService adminOAuth2TokenService;

    @Override
    public AdminAuthLoginRespVO login(AuthLoginReqVO authLoginReqVO) {
        AdminUserDO user = authenticate(authLoginReqVO.getUsername(), authLoginReqVO.getPassword());

        return createTokenAfterLoginSuccess(user.getId(), user.getUsername());
    }

    private AdminAuthLoginRespVO createTokenAfterLoginSuccess(Long userId, String username) {
        AdminOAuth2AccessTokenDO accessTokenDO = adminOAuth2TokenService.createAccessToken(userId, username);

        return new AdminAuthLoginRespVO().setUserId(accessTokenDO.getUserId())
                .setAccessToken(accessTokenDO.getAccessToken())
                .setRefreshToken(accessTokenDO.getRefreshToken())
                .setExpiresTime(accessTokenDO.getExpiresTime());
    }

    private AdminUserDO authenticate(String username, String password) {
        AdminUserDO user = adminUserService.getUserByUsername(username);
        if (Objects.isNull(user)) {
            throw new RuntimeException("user is not exist");
        }
        if (!adminUserService.isPasswordMatch(password, user.getPassword())) {
            throw new RuntimeException("password is error");
        }
        return user;
    }
}
